package dfl.bysj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import dfl.bysj.config.RedisKey;
import dfl.bysj.entity.Seat;
import dfl.bysj.mapper.SeatMapper;
import dfl.bysj.service.SeatService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author DFL
 * @since 2022-04-26
 */
@Service
public class SeatServiceImpl extends ServiceImpl<SeatMapper, Seat> implements SeatService {
    private RedisTemplate redisTemplate;


    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private List<Seat> seats;

    private AtomicReference<Seat> seatAtomicReference= new AtomicReference<>(new Seat());




    private void getSeats(){
        seats= (List<Seat>) redisTemplate.opsForValue().get(RedisKey.ALL_SEAT);
        if (seats==null){
            updateRedisOfSeats();

        }
    }

    private void updateRedisOfSeats(){
        seats=list();
        redisTemplate.opsForValue().set(RedisKey.ALL_SEAT,seats,7, TimeUnit.DAYS);
    }

    @Override
    public List<Seat> getAllSeats() {
        getSeats();
        return seats;
    }

    @Override
    public Integer getSeatCount() {
        getSeats();
        return seats.size();
    }

    @Transactional
    @Override
    public List getSeatByFloId(Integer floId) {
        getSeats();
        List<Seat> seatList=new ArrayList();
        seats.stream()
                .filter(s->s.getFloId()==floId)
                .forEach(seatList::add);

        return seatList;
    }

    @Override
    public Seat getSeaNumBySeaId(Integer seaId) {
        getSeats();
        seats.stream()
                .filter(s->s.getSeaId()==seaId)
                .forEach(s-> seatAtomicReference.set(s));
        if (seatAtomicReference.get().getSeaId()==null){
            return null;
        }
        return seatAtomicReference.get();
    }

    @Override
    public void updateSeatPic(Integer seaId, String fileID) {
        Seat seat=new Seat();
        seat.setSeaPicture(fileID);
        update(seat, new QueryWrapper<Seat>()
                .eq("sea_id", seaId));

        updateRedisOfSeats();
    }


}
